package com.lhd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lhd.mapper.UserMapper;
import com.lhd.pojo.PageBean;
import com.lhd.pojo.PageCondition;
import com.lhd.pojo.User;
import com.lhd.service.UserService;
import com.lhd.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(User user) {
        return userMapper.findByUserNameAndPasswordOrPhone(user);
    }

    @Override
    public void register(User user) {
        userMapper.add(user);
    }

    @Override
    public User getInfo() {
        Integer id = getId();
        return userMapper.getInfo(id);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Integer id = getId();
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updateUsername(String username) {
        Integer id = getId();
        userMapper.updateUsername(username, id);
    }

    @Override
    public void updatePassword(String password) {
        Integer id = getId();
        userMapper.updatePassword(password, id);
    }

    @Override
    public void updatePtsAndCrs(Integer credit, Integer pts) {
        Integer id = getId();
        userMapper.updatePtsAndCrs(credit, pts, id);
    }

    @Override
    public List<User> getOrder() {
        Integer id = getId();
        return userMapper.getOrder(id);
    }

    @Override
    public PageBean<User> getWithCondition(String username,Integer credit,Integer identity,Integer point, PageCondition pageCondition) {
        PageHelper.startPage(pageCondition.getPageNum(),pageCondition.getPageSize());
        Page<User> page = userMapper.getWithCondition(username,credit,identity,point);
        long total = page.getTotal();
        List<User> result = page.getResult();
        return new PageBean<>(total,result);
    }

    @Override
    public void updateCredit(Integer credit,Integer id) {
        userMapper.updateCredit(credit,id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void remove(Integer id) {
        userMapper.remove(id);
    }

    private Integer getId() {
        Map<String, Object> map = ThreadLocalUtil.get();
        return (Integer) map.get("id");
    }
}
